<template>
  <div class="d_main">
    <!-- 操作区 S-->
    <SelectSCorder :per-visible.sync="showOrder" @current="selectCurrentRow" />
    <div class="d_operationBox">
      <div class="d_btn">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="newAddClick"
          >新建申请</el-button
        >
      </div>
      <div class="d_search">
        <screec
          v-model="search.queryDataBaseFiled"
          :headData.sync="tableHead"
          :disabled="searchLoading"
        ></screec>
        <el-input
          v-model="search.likeWords"
          placeholder="请输入关键字"
          size="small"
          @keyup.enter.native="getAllMaterils"
        >
          <el-button
            slot="append"
            :loading="searchLoading"
            type="primary"
            icon="el-icon-search"
            :disabled="searchLoading"
            element-loading-spinner="el-icon-loading"
            @click="getAllMaterils"
          >
            搜索
          </el-button>
        </el-input>
      </div>
    </div>
    <!-- 操作区 E-->
    <!-- 表格操作区 S-->
    <div class="d_tableOperation">
      <div class="d_condition"></div>
      <div class="d_set">
        <div @click="Refresh"><i class="d_icon el-icon-refresh-right" /></div>
        <div class="setting flex">
          <HeadSeting
            :list-data.sync="tableHead"
            :table-code="$config.producebackmaterialbilllist"
            @reset="getTableHead"
          />
        </div>
      </div>
    </div>
    <!-- 表格操作区 E-->
    <!--table板块-->
    <div ref="tableCon" class="tableCon expandBox">
      <el-table
        v-show="tableHead.length > 0"
        id="emtable"
        ref="multipleTable"
        v-loading="searchLoading"
        :data="allMaterirls"
        :height="tableHeight || 'auto'"
        border
        fit
        style="width: 100%"
        @header-dragend="surverWidth"
      >
        <template v-for="(fruit, index) in tableHead">
          <el-table-column
            v-if="fruit.visible"
            :key="index"
            :label="fruit.columnName"
            :min-width="fruit.columnWidth || 90"
            :prop="fruit.columnCode"
            show-overflow-tooltip
            :fixed="fruit.isFloat ? 'left' : false"
          >
            <template slot-scope="scope">
              <div v-if="fruit.columnCode === 'applyBillStateName'">
                <template>
                  <el-tag
                    v-if="scope.row.applyBillState == 0"
                    size="small"
                    >{{ scope.row[fruit.columnCode] }}</el-tag
                  >
                  <el-tag
                    v-else-if="scope.row.applyBillState == 1"
                    type="success"
                    size="small"
                    >{{ scope.row[fruit.columnCode] }}</el-tag
                  >
                  <el-tag
                    v-else-if="scope.row.applyBillState == 2"
                    type="warning"
                    size="small"
                    >{{ scope.row[fruit.columnCode] }}</el-tag
                  >
                  <el-tag
                    v-else
                    type="danger"
                    size="small"
                    >{{ scope.row[fruit.columnCode] }}</el-tag
                  >
                </template>
              </div>
              <template v-else>
                {{ scope.row[fruit.columnCode] }}
              </template>
            </template></el-table-column
          >
        </template>
        <el-table-column label="操作" width="70px" fixed="right" align="center">
          <template slot-scope="scope">
            <div>
              <el-popover
                :ref="`popover-${scope.$index}`"
                placement="bottom-end"
                popper-class="tableOp"
                width="160"
                :popper-options="{
                  boundariesElement: 'opBox',
                  removeOnDestroy: true,
                }"
                trigger="click"
              >
                <div class="operation">
                  <ul>
                    <li v-if="scope.row.applyBillState != 0" @click="handleClick(scope.row)">查看</li>
                    <li v-if="scope.row.applyBillState == 0" @click="handleUpdata(scope.row)">修改</li>
                  </ul>
                  <ul>
                    <li v-if="scope.row.applyBillState == 0"  @click="handleConfirm(scope.row)">确认</li>
                    <li v-if="scope.row.applyBillState == 1" @click="handleCancel(scope.row)">取消</li>
                    <li v-if="scope.row.applyBillState == 3" @click="handleCopy(scope.row)">复制</li>
                  </ul>
                  <ul>
                    <li v-if="scope.row.applyBillState == 0" @click="handleDelete(scope.row)">删除</li>
                  </ul>
                </div>
                <div slot="reference" class="opBox pointer">
                  <span class="el-icon-more c_3F61F1" />
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 骨架屏     -->
      <div v-if="tableHead.length == 0" class="p16">
        <el-skeleton :rows="6" animated />
      </div>
    </div>
    <!-- 分页 S-->
    <div class="d_pag">
      <pagination
        :total="total || 0"
        :page.sync="search.pageIndex"
        :limit.sync="search.pageSize"
        @pagination="getAllMaterils"
      />
    </div>
    <!-- 分页 E-->
    <!-- 人员寻找弹框   -->
    <per-redio-dialog
      :per-visible.sync="isperShow"
      @getEmployee="getEmployee"
    />
    <el-dialog
      :title="tname"
      :visible.sync="isAddProduct"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
      @open="getMachineList"
    >
      <div class="dialogDody">
        <div class="addWuliaoBox">
          <el-form
            ref="ProductForm"
            :model="ProductForm"
            :rules="rules"
            label-width="110px"
            label-position="top"
            class="dialogForm dialogInlineForm"
            :disabled="canDiable"
          >
            <div class="cTitle">
              <h3>申请信息</h3>
            </div>
            <el-row>
              <el-col :span="8">
                <el-form-item label="申请单号" prop="applyBillNo">
                  <el-input
                    v-model="ProductForm.applyBillNo"
                    placeholder="系统自动生成"
                    disabled
                    size="small"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请人员" prop="applyPersonName">
                  <el-input
                    :value="ProductForm.applyPersonName || name"
                    placeholder="请填写申请人员"
                    disabled
                    size="small"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-input
                    :value="ProductForm.applyTime || date"
                    placeholder="请填写申请时间"
                    size="small"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="订单单号" prop="xieYiShuHao">
                  <el-input
                    v-model="ProductForm.xieYiShuHao"
                    placeholder="请填写订单单号"
                    size="small"
                    disabled
                  >
                    <el-button
                      slot="append"
                      icon="el-icon-search"
                      @click="showOrder = true"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品名称" prop="orderProductName">
                  <el-input
                    v-model="ProductForm.orderProductName"
                    placeholder="选择订单后自动带出"
                    size="small"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请机台" prop="applyMachine">
                  <el-select
                        filterable
                    v-model="ProductForm.applyMachine"
                    placeholder="请选择申请机台"
                    size="mini"
                    filterable
                  >
                    <el-option
                      v-for="item in equipmentList"
                      :key="item.machineCode"
                      :label="item.machineName"
                      :value="item.machineCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="板数" prop="plateQuantity">
                  <el-input
                    v-model="ProductForm.plateQuantity"
                    placeholder="请填写板数"
                    size="small"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="版面" prop="knifeVersion">
                <el-select
                        filterable
                    v-model="ProductForm.knifeVersion"
                    placeholder="请选择版面"
                    size="small"
                    filterable
                  >
                    <el-option label="新版" value="新版"/>
                    <el-option label="旧版" value="旧版"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- <el-form-item label="损坏模板编号" prop="knifeVersionNo">
                  <el-input
                    v-model="ProductForm.knifeVersionNo"
                    placeholder="请填写损坏模板编号"
                    size="small"
                  />
                </el-form-item> -->
                <el-form-item label="损坏模板名称" prop="knifeVersionName">
                <el-select
                        filterable
                    v-model="ProductForm.knifeVersionName"
                    placeholder="请选择损坏模板名称"
                    size="small"
                    filterable

                  >
                    <el-option
                      v-for="item in selectList"
                      :key="item.knifeVersionID"
                      :label="item.knifeVersionName"
                      :value="item.knifeVersionNo"
                      @click.native="handleSelectChange(item.knifeVersionName,item.knifeVersionNo)"
                    >
                    <span style="float: left">{{ item.knifeVersionName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.knifeVersionNo }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="申请原因" class="applyReson">
                  <el-input
                    v-model="ProductForm.applyReson"
                    type="textarea"
                    :rows="3"
                    placeholder="请填写申请原因"
                    size="small"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddProduct = false">取 消</el-button>
        <!-- 新增       -->
        <el-button
          v-if="opsid !== 2"
          :loading="addProductLoading"
          :disabled="addProductLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="savell"
          >{{ btm }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { arraySort } from "@/utils";
import HeadSeting from "@/components/HeadSeting";
import Pagination from "@/components/Pagination";
import perRedioDialog from "@/components/perDialogRedio";
import selectProductOrder from "@/components/selectProductOrder";
import screec from "@/components/screen";
import SelectSCorder from "@/components/selectSCorder";
import { mapGetters } from "vuex";

export default {
  name: "editionAdmin",
  components: {
    Pagination,
    HeadSeting,
    perRedioDialog,
    selectProductOrder,
    screec,
    SelectSCorder,
  },
  data() {
    return {
      ops: "add", // 操作、新建，修改，查看
      opsid: 1, // 3 确定 1 新建， 4 修改， 2 查看
      tableHeight: null, // 表格最大高度
      isSeeMaterriel: false, // 查看弹框是否打开
      isAddMaterriel: false, // 新建弹框是否打开
      addMaterrielLoading: false, // 新建保存加载
      searchLoading: false, // 搜索加载效果
      allMaterirls: [], // 全部数据列表
      colorState: null,
      addLoading: false,
      isNopassshow: false,
      equipmentList: [],
      showOrder: false,
      passForm: {
        cancelReason: "",
      },
      // 表格操作
      ProductForm: {
        applyBillNo: "", //刀版申请单号
        applyPersonName: "", //申请人员姓名
        applyTime: "", //申请时间（创建时间）
        xieYiShuHao: "", //订单单号
        orderProductName: "", //订单产品名称
        knifeVersionNo: "", //	损坏刀版（刀版编码）
        knifeVersionName: "", //损坏刀版名称
        saleOrderNo: "", //	业务订单号
        applyMachine: "", //申请机台（机台代码）
        plateQuantity: "", //板数
        knifeVersion: "", //版面：新版；旧版
        applyReson: "", //申请原因
      },
      // 搜索条件
      search: {
        queryDataBaseFiled: "",
        pageIndex: 1,
        pageSize: 30,
        likeWords: "",
        applyBillState: -1, //单据状态：0待确认；1待审核（已确认）；2已完成（审核通过）；3已拒绝（审核未通过），-1查询全部
        checkResult: -1, //	审核结果：0未审核；1审核通过；2审核拒绝，-1查询全部
      },
      total: 0, // 总条数
      tableHead: [], // 表格表头
      addProductLoading: false,
      isAddProduct: false,
      rowData: "",
      isperShow: false,
      isSemidialog: false,
      multipleSelection: null,
      materialList: [],
      selectList:[],
      queryExamine: {
        //审核列表查询参数
        applyBillState: -1, //单据状态：0待确认；1待审核（已确认）；2已完成（审核通过）；3已拒绝（审核未通过），-1查询全部
        checkResult: 0, //审核结果：0未审核；1审核通过；2审核拒绝，-1查询全部
        likeWords: "",
      },
      marLoading: false,
      canDiable: false,
      rules: {
        xieYiShuHao: [
          { required: true, message: "请选择订单单号", trigger: "blur" },
        ],
        applyMachine: [
          { required: true, message: "请选择申请机台", trigger: "blur" },
        ],
        plateQuantity: [
          { required: true, message: "请输入板数", trigger: "blur" },
        ],
        knifeVersion: [
          { required: true, message: "请选择版面", trigger: "change" },
        ],
        knifeVersionName: [
          { required: true, message: "请选择损坏刀版名称", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["name", "userInfo"]),
    btm() {
      if (this.opsid === 3) {
        return "确认";
      } else {
        return "保存";
      }
    },
    tname() {
      if (this.opsid === 1) {
        return "新建刀版申请";
      } else if (this.opsid === 2) {
        return "查看刀版申请";
      } else if (this.opsid === 3) {
        return "确定刀版申请";
      } else if (this.opsid === 4) {
        return "修改刀版申请";
      } else {
        return "复制刀版申请";
      }
    },
  },
  created() {
    //  所有列表数据
    this.getAllMaterils();
    // 表格得表头
    this.getTableHead();
    //获取损坏模板列表
    this.getListVersionList()
    let time = new Date();
    this.date = time.toLocaleDateString().replace(/\//g, "-"); //获取当前日期
  },
  mounted() {
    // 表格高度
    this.calHeight();
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.multipleTable.doLayout();
    });
  },
  methods: {
    closePassDialog() {
      this.passForm.cancelReason = "";
    },
    //获取损坏模板列表
    getListVersionList(){
      this.$api.product.GetMatchKnifeVersionDataList({likeWords:''}).then((res)=>{
        this.selectList = res
      })
    },


    // 新建点击事件
    newAddClick() {
      this.ops = "add";
      this.isAddProduct = true;
      this.opsid = 1;
      this.canDiable = false;
    },
    //查看
    handleClick(row) {
      this.opsid = 2;
      this.canDiable = true;
      this.getDetail(row);
    },

    //损坏模板选择事件
    handleSelectChange(label,value){
      this.ProductForm.knifeVersionNo = value
      this.ProductForm.knifeVersionName = label
    },

    //确定
    handleConfirm(row) {
      this.opsid = 3;
      // this.canDiable = true;
      this.rowData = row;
      this.getDetail(row);
    },

    //取消审核
    handleCancel(row) {
      this.$confirm("是否确定取消本次审核?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.product
          .CancelKnifeVersionApplyCheck({applyID:row.applyID})
          .then(() => {
            this.getAllMaterils();
            this.$message({
              message: "取消成功",
              type: "success",
            });
          })
          .catch(() => {});
      });
    },

    //复制
    handleCopy(row) {
      this.opsid = 5;
      this.canDiable = false;
      this.getDetail(row);
    },

    //修改
    handleUpdata(row) {
      this.opsid = 4;
      this.canDiable = false;
      this.getDetail(row);
    },


    //获取审核列表
    MarterdialogShow() {
      this.$api.product
        .GetMatchKnifeVersionApplyList(this.queryExamine)
        .then((res) => {
          this.materialList = res;
        });
    },

    //获取机台下拉
    getMachineList(){
      const _data = {
        OwnDepartment: 1,
        MachineState:1,
        likeWords: "",
      };
      this.$api.product.GetMatchProductDevices(_data).then((res) => {
        this.equipmentList = res;
      });
    },

    //订单选中数据
    selectCurrentRow(row) {
      this.ProductForm.saleOrderNo = row.saleOrderNo;
      this.ProductForm.xieYiShuHao = row.xieYiShuHao;
      this.ProductForm.orderProductName = row.orderProductName;
      this.$refs['ProductForm'].clearValidate('xieYiShuHao')

    },

    //删除
    handleDelete(row) {
      const _data = {
        applyID: row.applyID,
      };
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.product
          .DeleteKnifeVersionApply(_data)
          .then(() => {
            this.getAllMaterils();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          })
          .catch(() => {});
      });
    },
    getDetail(row) {
      const _data = {
        applyID: row.applyID,
        applyBillNo: "",
      };
      this.$api.product.GetKnifeVersionApplyDetail(_data).then((res) => {
        this.ProductForm = res;
        if (this.opsid == 5) {
          this.ProductForm.applyBillNo = "";
        }
        this.isAddProduct = true;
      });
    },
    savell() {
      if (this.opsid === 1 || this.opsid === 5) {
        this.$refs.ProductForm.validate((valid) => {
          if (valid) {
            this.addProductLoading = true;
            this.$api.product
              .CreateKnifeVersionApply(this.ProductForm)
              .then(() => {
                this.addProductLoading = false;
                this.isAddProduct = false;
                this.getAllMaterils();
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
              })
              .catch(() => {
                this.addProductLoading = false;
              });
          }
        });
      } else if (this.opsid === 4) {
        this.$refs.ProductForm.validate((valid) => {
          if (valid) {
            this.addProductLoading = true;
            this.$api.product
              .UpdateKnifeVersionApply(this.ProductForm)
              .then(() => {
                this.addProductLoading = false;
                this.isAddProduct = false;
                this.getAllMaterils();
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
              })
              .catch(() => {
                this.addProductLoading = false;
              });
          }
        });
      } else if (this.opsid === 3) {
        this.$refs.ProductForm.validate((valid) => {
          if (valid) {
            this.addProductLoading = true;
            this.$api.product
              .SureKnifeVersionApply({
                applyID: this.rowData.applyID,
              })
              .then(() => {
                this.addProductLoading = false;
                this.isAddProduct = false;
                this.getAllMaterils();
                this.$message({
                  message: "确认成功",
                  type: "success",
                });
              })
              .catch(() => {
                this.addProductLoading = false;
              });
          }
        });
      }
    },

    // 得到申请人员
    getEmployee(val) {
      this.ProductForm.backMaterialPersonName = val.employeeName;
      this.ProductForm.getMaterialPerson = val.employeeCode;
    },
    closeSemiDialog() {
      this.isSemidialog = false;
    },
    // 保存表头样式变化
    saveHead(newArray) {
      const parmas = newArray;
      setTimeout(() => {
        this.$api.common.saveTableStyle(parmas).then(() => {});
      }, 300);
    },
    // 保存表头列宽度
    surverWidth(newWidth, oldWidth, column) {
      setTimeout(() => {
        const heads = [...this.tableHead];
        heads.forEach((item) => {
          if (item.columnCode === column.property) {
            item.columnWidth = column.width;
            return;
          }
        });
        this.saveHead(heads);
      }, 100);
    },
    // 表格最大高度
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.tableCon.getBoundingClientRect();
        this.tableHeight = rect.height;
      });
    },
    // ，清除所有查询条件
    Refresh() {
      this.search = this.$options.data().search;
      this.getAllMaterils();
    },
    // 获取表格表头
    getTableHead() {
      const parmas = {
        tableCode: this.$config.KnifeVersionApplyPageList,
      };
      this.$api.common.getAllTableHead(parmas).then((res) => {
        res.sort(arraySort("columnSort"));
        this.tableHead = res;
      });
    },
    // 所有列表数据
    getAllMaterils() {
      const parmas = this.search;
      this.searchLoading = true;
      this.$api.product
        .GetPageKnifeVersionApplyDataList(parmas)
        .then((res) => {
          this.allMaterirls = res.list;
          this.allMaterirls.forEach((item) => {
            for (let i in item) {
              if (!item[i] && item[i] !== 0) {
                item[i] = "--";
              }
            }
          });
          this.total = res.totalCount;
          this.searchLoading = false;
        })
        .catch(() => {
          this.searchLoading = false;
        });
    },
    // 新建弹框关闭事件
    closeDialog() {
      if (this.$refs.ProductForm) {
        this.$refs.ProductForm.resetFields();
      }
      this.ProductForm = this.$options.data().ProductForm;
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  height: 100%;
}
.permangeRg {
  border: 1px solid #e6e6e6;
  background: #fff;
  height: 100%;

  .mainTT {
    font-size: 16px;
    font-weight: bold;
    width: 100%;
    padding: 18px 16px;
    padding-bottom: 0;
  }
}
.addWuliaoBox {
  padding: 10px 16px;

  .tableBox {
    margin-top: 16px;
    border: 1px solid #e6e6e6;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    overflow: hidden;

    .tt {
      height: 38px;
      line-height: 38px;
      padding-left: 16px;
      background: #f7f8fa;
      border-radius: 8px 8px 0 0;
    }
  }
}
::v-deep .el-form-item__label {
  padding-bottom: 0 !important;
  padding-left: 8px;
}
.subTip {
  border-bottom: 1px #e6e6e6 solid;
  background: #f5f6f9;
  padding: 8px 16px;
}
</style>
